package com.marker.mo.amapsmoothmarker;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.widget.Button;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.utils.SpatialRelationUtil;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import okhttp3.Call;

/**
 * 高德地图，仿滴滴车辆在地图上随机平滑移动Demo
 */
public class MainActivity2 extends AppCompatActivity {

    private MapView mMapView = null;
    private AMap aMap;
    private List<LatLng> startLatLngs = new ArrayList<>();
    //静态车辆的数据
    private List<List<LatLng>> newLatLngs = new ArrayList<>();
    private List<MySmoothMoveMarker> smoothMarkers = new ArrayList<>();//平滑移动图标集合
    private int carNum = 2;// 生成车辆数目
    private LatLng centerLatLng = new LatLng(38.049977, 114.430253);
    private Circle mCircle;
    public static final int STROKE_COLOR = Color.parseColor("#384D73B3");// 定位范围线条颜色
    public static final int FILL_COLOR = Color.parseColor("#384D73B3");// 定位范围的填充颜色
    private Button start, reset, reset100;
    private CircleOptions options;
    private boolean isfirst = true;
    private List<BusBean.ListBean> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.map);
        mMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        aMap.getUiSettings().setRotateGesturesEnabled(false);
        initView();

    }

    private void initView() {
        aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(
                centerLatLng, 16, 0, 0)));
        start = (Button) findViewById(R.id.put);
        reset = (Button) findViewById(R.id.run);
        reset100 = (Button) findViewById(R.id.run100);

        options = new CircleOptions();
        options.strokeWidth(1f);
        // 设置透明圆形图层
//        options.fillColor(Color.argb(0, 0, 0, 255));
//        options.strokeColor(Color.argb(0, 0, 0, 255));
        options.fillColor(STROKE_COLOR);
        options.strokeColor(FILL_COLOR);
        options.center(centerLatLng);
        options.radius(500);

        /**
         * 展示平滑移动车辆
         */
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                aMap.clear();//清空地图覆盖物
//                mCircle = aMap.addCircle(options);
//                if (smoothMarkers != null){
//                    if (smoothMarkers.size() != 0){
//                        for (int i = 0; i < smoothMarkers.size(); i++) {
//                            smoothMarkers.get(i).destroy();
//                        }
//                    }
//                }
//                smoothMarkers = new ArrayList<MySmoothMoveMarker>();
//
//                for (int i = 0; i < carNum; i++) {
//                    List<LatLng> latLng = randomGenerateLatLngs(startLatLngs.get(i));
//                    startMoveCar(latLng, i, true);
//                }
                mHandler.postDelayed(r, 100);//延时100毫秒

            }
        });

        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                LogUtil.e("marker id" + marker.getId());
                return true;
            }
        });

    }


    /**
     * 生成以中心点附近指定radius内的坐标数组
     *
     * @param startLatLng 起点坐标
     * @return
     */
    private ArrayList<LatLng> randomGenerateLatLngs(LatLng startLatLng) {
        ArrayList<LatLng> latLngs = new ArrayList<>();
        latLngs.add(startLatLng);
        double lat = centerLatLng.latitude;
        double lng = centerLatLng.longitude;
        for (int i = 0; i < 50; i++) {
            double newLat = lat + (10 - (Math.random() * 20)) / Math.pow(10, new Random().nextInt(3) + 1);
            double newLng = lng + (10 - (Math.random() * 20)) / Math.pow(10, new Random().nextInt(3) + 1);
            LatLng newLatLng = new LatLng(newLat, newLng);
            if (mCircle.contains(newLatLng)) {
                latLngs.add(newLatLng);
            }
        }
        // 如果随机生成的数组个数为0，则再随机添加一个距离中心点更近的坐标
        if (latLngs.size() == 1) {
            latLngs.add(new LatLng(lat + (Math.random() > 0.5 ? 1 : -1) / Math.pow(10, 3), lng + (Math.random() > 0.5 ? 1 : -1) / Math.pow(10, 3)));
        }
        return latLngs;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }


    /**
     * 获取个人信息
     *
     * @param path
     */
    public void getUserData(String path) {
        try {
            OkHttpUtils
                    .post()
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("User-Agent", " Mozilla/5.0 (Linux; Android 6.0.1; MI 5LTE Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 Mobile Safari/537.36 MicroMessenger/7.0.4.1420(0x2700043C) Process/appbrand0 NetType/WIFI Language/zh_CN")
                    .addParams("CMD", "104")
                    .addParams("CITYNAME", "石家庄市")
                    .addParams("LINENAME", "314路")
                    .addParams("DIRECTION", "1")
                    .url(path)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            LogUtil.e("出错" + e.getMessage());
                        }

                        @Override
                        public void onResponse(String string, int id) {
//                            LogUtil.e(string);
                            Gson gson = new Gson();
                            BusBean codeMsgBean = gson.fromJson(string, BusBean.class);
                            list = codeMsgBean.getList();
                            if (startLatLngs.size() > 2) {
                                if (startLatLngs.get(0).latitude == startLatLngs.get(1).latitude&&startLatLngs.get(0).longitude == startLatLngs.get(1).longitude) {
                                    LogUtil.e("位置不变" );
                                    return;
                                }
                            }
                            startLatLngs.add(new LatLng(list.get(0).getBus_lat(), list.get(0).getBus_lng()));
                            if (startLatLngs.size() == 3) {
                                startLatLngs.remove(0);

                            }
                            startMoveCar(startLatLngs, 0, isfirst);


//                            startLatLngs = new ArrayList<>();
//                            for (int i = 0; i < list.size(); i++) {
//                                startLatLngs.add(new LatLng(list.get(i).getBus_lat(), list.get(i).getBus_lng()));
//                            }
//                            newLatLngs.add(startLatLngs);
//                            if (newLatLngs.size() > 3) {
//                                for (int i = 0; i < list.size(); i++) {
//                                    ArrayList<LatLng> latLngs = new ArrayList<>();
//                                    for (int j = 0; j < newLatLngs.size(); j++) {
//                                        latLngs.add(newLatLngs.get(j).get(i));
//                                    }
//                                    startMoveCar(latLngs, i, isfirst);
//                                }
//                                isfirst = false;
//                                newLatLngs.clear();
//                            }

                        }

                    });

        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.e("个人信息出错了....");
        }
    }


    /**
     * 开始平滑移动车辆
     *
     * @param latLngs 车辆轨迹坐标数组
     * @param index   车辆序号
     * @param isFirst 是否首次移动
     */

    public void startMoveCar(List<LatLng> latLngs, final int index, boolean isFirst) {
        Log.i("latLngs的大小", latLngs.size() + "");
        BitmapDescriptor descriptor = BitmapDescriptorFactory.fromResource(R.drawable.car_up_white);
        // 获取轨迹坐标点
        List<LatLng> points = new ArrayList<>(latLngs);
        for (int i = 0; i < points.size(); i++) {
            LogUtil.e("points " + points.size() + "位置" + points.get(i).latitude + "," + points.get(i).longitude);
        }
        MySmoothMoveMarker smoothMarker;
        if (isFirst) {
            smoothMarker = new MySmoothMoveMarker(aMap);
            smoothMarkers.add(smoothMarker);
            isfirst = false;
        } else {
            smoothMarker = smoothMarkers.get(index);
        }
//        smoothMarker.setRotate((float) list.get(0).getAngle());
        // 设置滑动的图标
        smoothMarker.setDescriptor(descriptor);
        LatLng drivePoint = points.get(0);
        Pair<Integer, LatLng> pair = SpatialRelationUtil.calShortestDistancePoint(points, drivePoint);
        points.set(pair.first, drivePoint);
        List<LatLng> subList = points.subList(pair.first, points.size());

        // 设置滑动的轨迹左边点
        smoothMarker.setPoints(subList);
        // 设置滑动的总时间
        smoothMarker.setTotalDuration(subList.size() * 4);
        smoothMarker.setMoveListener(new MySmoothMoveMarker.MoveListener() {
            @Override
            public void move(double v) {

            }

            @Override
            public void stop(LatLng latLng) {
                LogUtil.e("动画完成");
//                getUserData("https://wx.shenghuoquan.cn/WxBusServer/ApiData.do");
            }
        });
        // 开始滑动
        smoothMarker.startSmoothMove();
    }

    final Handler mHandler = new Handler();
    Runnable r = new Runnable() {

        @Override
        public void run() {
            getUserData("https://wx.shenghuoquan.cn/WxBusServer/ApiData.do");
            //每隔1s循环执行run方法
            mHandler.postDelayed(this, 8000);
        }
    };
}
